import React, { useMemo } from 'react';
import { TreeSelect, Select } from 'antd';
import { isDataTypeMatch } from '../../utils/dataType';
import styled from 'styled-components';

const OptionLabel = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
`;

const OptionValue = styled.span`
  float: left;
`;

const OptionName = styled.span`
  float: right;
  color: var(--ant-text-color-secondary);
  font-size: 13px;
  margin-left: 5px;
`;

const VariableSelect = ({
  value,
  onChange,
  options = [],
  filterDataType,
  size = 'default',
}) => {
  const innerOptions = useMemo(() => {
    return (options || [])
      .map(option => {
        const newItem = {
          label: option.envName,
          value: option.envKey,
        };
        if (handleShowObject(option.dataType, newItem.value)) {
          return {
            ...newItem,
            children: getOptionChildren(option.dataType, newItem.value),
          };
        }
        return null;
      })
      .filter(item => item !== null);
  }, [options, filterDataType]);

  const hasObjectOption = useMemo(() => {
    return options?.some(item => item.dataType.type === 'Object');
  }, [options]);

  function handleShowObject(dataType, preValue) {
    if (dataType.type === 'List' && filterDataType?.type === 'List' && dataType.itemType !== filterDataType.itemType) {
      return false;
    }
    if (dataType.type !== 'Object') {
      return true;
    }
    const propList = getOptionChildren(dataType, preValue);
    if (filterDataType) {
      if (filterDataType.type === 'Object') {
        return filterDataType.type === dataType.type;
      } else {
        if (propList?.length === 0) {
          return false;
        }
      }
    }
    return true;
  }

  function getOptionChildren(dataType, preValue, count = 0) {
    if (dataType.type === 'Object') {
      if (count > 99) {
        return;
      }
      let list = dataType.objectStructure || [];
      if (filterDataType) {
        list = list.filter(item => isDataTypeMatch(item.dataType, filterDataType));
      }
      return list.map(item => {
        const newItem = {
          label: item.propName,
          value: preValue + '.' + item.propKey,
        };
        return {
          ...newItem,
          children: getOptionChildren(item.dataType, newItem.value, count + 1),
        };
      });
    }
  }

  const handleChange = (val) => {
    onChange?.(val);
  };

  function getLabel(val) {
    if (!val) return '';
    const arr = val.split('.');
    let key = arr.shift();
    let parent = innerOptions?.find(item => item?.value === key);
    let result = parent?.label;
    while (parent && arr.length > 0) {
      key = key + '.' + arr.shift();
      parent = parent?.children?.find(item => item.value === key);
      if (parent) {
        result += '.' + parent.label;
      }
    }
    return result;
  }

  if (hasObjectOption) {
    return (
      <TreeSelect
        value={value}
        treeData={innerOptions}
        treeNodeFilterProp="label"
        showCheckedStrategy={TreeSelect.SHOW_CHILD}
        size={size}
        onChange={handleChange}
        treeNodeLabelProp="label"
        labelInValue={false}
        treeDefaultExpandAll
      />
    );
  }

  return (
    <Select
      value={value}
      size={size}
      onChange={handleChange}
      style={{ width: '100%' }}
    >
      {innerOptions.map(item => (
        <Select.Option key={item?.value} value={item?.value} title={item?.label}>
          <OptionLabel>
            <OptionValue>{item.value}</OptionValue>
            <OptionName>{item.label}</OptionName>
          </OptionLabel>
        </Select.Option>
      ))}
    </Select>
  );
};

export default VariableSelect; 